'''
    股票查询
'''
import os
import json
import random
from backend import settings
from django.http import JsonResponse
from thirdparty import juhe
from utils.response import CommonResponseMixin, ReturnCode
from utils.auth import already_authorized, get_user
from django.core.cache import cache
from utils.timeutil import get_day_left_in_second
import logging
logger = logging.getLogger('django') # 在 settings.LOGGING.loggers 配置

# 默认股票
POPULAR_STOCKS = [
    {
        'code': '000001',
        'name': '平安银行',
        'market': 'sz'
    }, {
        'code': '000002',
        'name': '万科A',
        'market': 'sz'
    }, {
        'code': '600036',
        'name': '招商银行',
        'market': 'sh'
    }, {
        'code': '601398',
        'name': '工商银行',
        'market': 'sh'
    }
]


# 默认星座
CONSTELLATIONS = ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座']


# 所有笑话
all_jokes = []


# 股票查询
def stock(request):
    data = []
    stocks = []
    if already_authorized(request):
        user = get_user(request)
        stocks = json.loads(user.focus_stocks)
    else:
        stocks = POPULAR_STOCKS

    for stock in stocks:
        result = juhe.stock(market=stock['market'], code=stock['code'])
        data.append(result)
    response = CommonResponseMixin.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
    return JsonResponse(data=response, safe=False)


# 星座运势
def constellation(request):
    data = []
    if already_authorized(request):
        user = get_user(request)
        constellations = json.loads(user.focus_constellations)
    else:
        constellations = CONSTELLATIONS

    for c in constellations:
        result = cache.get(c)
        if not result:
            result = juhe.constellation(c)
            timeout = get_day_left_in_second()
            cache.set(c, result, timeout)
            logger.info("set cache key=[%], value=[%s], timeout=[%d]" % (c, result, timeout))
        data.append(result)

    response = CommonResponseMixin.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
    return JsonResponse(data=response, safe=False)


# 每日笑话
def joke(request):
    global all_jokes # 将 all_jokes 定义为全局变量，以减少资源消耗
    # 判断是否有缓存
    if not all_jokes:
        all_jokes = json.load(open(os.path.join(settings.JOKES_DIR, 'jokes.json'), 'r'))
    LIMITS = 10
    sample_jokes = random.sample(all_jokes, LIMITS)
    response = CommonResponseMixin.wrap_json_response(data=sample_jokes, code=ReturnCode.SUCCESS)
    return JsonResponse(data=response, safe=False)
